package com.zcup.fileupload.controller;

import com.zcup.fileupload.entity.File;
import com.zcup.fileupload.entity.User;
import com.zcup.fileupload.entity.vo.FileById;
import com.zcup.fileupload.service.FileService;
import com.zcup.fileupload.utils.FileUtils;
import com.zcup.fileupload.utils.UUIIDUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 根据用户id查询文件列表
     * @param httpSession 用户session
     * @param model 存放位置
     * @return 跳转到文件列表页面
     */
    @GetMapping("showAll")
    public String show(HttpSession httpSession, Model model){
        //获取session中用户信息
        User user = (User) httpSession.getAttribute("user");
        //根据用户id去查询用户文件列表
        List<FileById> filesById = fileService.getFilesById(user.getId());
        //将文件列表信息存入model中
        model.addAttribute("files",filesById);
        return "dashboard.html";
    }


    @PostMapping("uploadFile")
    public String upload(MultipartFile file,HttpSession session){
        if (file.isEmpty()) {
            System.out.println("文件上传失败");
            return "error.html";
        }
        String originalFilename = file.getOriginalFilename();
        // String[] fileName = originalFilename.split("\\.");

        String contentType = file.getContentType();

        long fileSize = file.getSize()/1024;

        User user = (User) session.getAttribute("user");

        if (user == null) {
            System.out.println("用户信息获取失败");
            return "error.html";
        }

        boolean b = FileUtils.saveFile(file, originalFilename);
        if (!b){
            System.out.println("文件保存失败");
            return "error.html";
        }
        File save = new File();
        save.setId(UUIIDUtils.randomStr()).setOriginName(originalFilename).setFileName(originalFilename)
                .setType(contentType).setSize(fileSize).setFlags(1).setCounts(0)
                .setGmtCreate(new Date()).setAuth("ALL").setUid(user.getId()).setUrl(FileUtils.localPath + originalFilename);
        fileService.saveFileInfo(save);
        return "redirect:/file/showAll";
    }

    @GetMapping("download")
    public void download(@RequestParam("id") String id, HttpServletResponse response) throws IOException {
        System.out.println(id);
        FileById file = fileService.getFileByFid(id);

        fileService.updateFileCounts(id);

        // String url = file.getUrl();
        FileInputStream fis = new FileInputStream(new java.io.File(FileUtils.localPath,file.getFileName()));
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(file.getFileName(),"UTF-8"));
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(fis,os);
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(os);
    }

    @GetMapping("delete")
    public String delFile(@RequestParam("id") String id){
        fileService.delFileById(id);
        return "redirect:/file/showAll";
    }
}
